package org.luxor.commons.core.config;

import org.luxor.commons.core.config.properties.XssFilterProperties;
import org.luxor.commons.core.constant.FilterOrdered;
import org.luxor.commons.core.xss.XssFilter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.DispatcherType;

/**
 * xss过滤器
 *
 * @author Mr.yan @date 2020/3/10
 */
@Configuration
@EnableConfigurationProperties({XssFilterProperties.class})
@ConditionalOnProperty(prefix = XssFilterProperties.PREFIX, name = "enabled", havingValue = "true")
public class XssFilterConfig {

    @Bean
    public FilterRegistrationBean<XssFilter> xssFilterRegistration(XssFilterProperties xssFilterProperties) {
        FilterRegistrationBean<XssFilter> registration = new FilterRegistrationBean<>();
        registration.setDispatcherTypes(DispatcherType.REQUEST);
        registration.setFilter(new XssFilter());
        registration.addUrlPatterns(xssFilterProperties.getUrlPatterns().split(","));
        registration.addInitParameter("excludedPages", xssFilterProperties.getExcludedPages());
        registration.setName("xssFilter");
        registration.setOrder(FilterOrdered.XSS_FILTER_PRECEDENCE.getOrder());
        return registration;
    }

}
